package cn.xspace.library.ui.activity;

import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.network.exception.HttpException;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.JSONUtil;
import com.xspace.android.xafcommon.util.PreferencesUtils;
import com.xspace.android.xafcommon.util.T;

import java.util.HashMap;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.R;
import cn.xspace.library.base.MyBaseActivity;
import cn.xspace.library.util.OkHttpUtils;
import cn.xspace.library.util.Tools;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class FindPwdActivity extends MyBaseActivity implements View.OnClickListener {

    private static final String TAG = FindPwdActivity.class.getSimpleName();

    private TitleBar mTitlebar;

    private EditText mEtInputMobile;
    private ProgressBar mLoadingIf;
    private EditText mEtPassword;
    private EditText mEtConfirmPassword;
    private EditText mEtVercode;
    private TextView mTvVercodeImg;
    private CheckBox mChkShowpwd;
    private Button mBtRegister;

    private boolean[] ifboo = {false, false, false, false};

    private String codeKey;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_find_pwd);

        mTitlebar = (TitleBar) findViewById(R.id.find_pwd_title);
        mEtInputMobile = (EditText) findViewById(R.id.et_input_mobile);
        mLoadingIf = (ProgressBar) findViewById(R.id.loading_if);
        mEtPassword = (EditText) findViewById(R.id.et_password);
        mEtConfirmPassword = (EditText) findViewById(R.id.et_confirm_password);
        mEtVercode = (EditText) findViewById(R.id.et_vercode);
        mTvVercodeImg = (TextView) findViewById(R.id.tv_vercode_img);
        mChkShowpwd = (CheckBox) findViewById(R.id.chk_showpwd);
        mBtRegister = (Button) findViewById(R.id.bt_register);
    }

    @Override
    protected void initListener() {
        mTitlebar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTvVercodeImg.setOnClickListener(this);
//        mChkShowpwd.setOnClickListener(this);
        mBtRegister.setOnClickListener(this);
        mEtInputMobile.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String phone = mEtInputMobile.getText().toString().trim();
                if (phone.length() == 11) {
//                    mLoadingIf.setVisibility(View.VISIBLE);
//                    checkPhoneState(phone);
                } else {
                    mLoadingIf.setVisibility(View.GONE);
                    Drawable drawable = getResources().getDrawable(R.drawable.offline_notebook_not_synced);
                    drawable.setBounds(0, 0, 60, 60);
                    mEtInputMobile.setError("您的手机号不足11位", drawable);
                    ifboo[0] = false;
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mEtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String pwd = mEtPassword.getText().toString().trim();
                if (pwd.length() >= 6) {
                    Drawable drawable = getResources().getDrawable(R.drawable.offline_notebook_synced);
                    drawable.setBounds(0, 0, 60, 60);
//                    if(ifboo[1]){
//                        edPass.setCompoundDrawables(null, null, drawable, null);
//                        return;
//                    }
                    mEtPassword.setError("正确", drawable);
                    ifboo[1] = true;
                } else {
                    Drawable drawable = getResources().getDrawable(R.drawable.offline_notebook_not_synced);
                    drawable.setBounds(0, 0, 60, 60);
                    mEtPassword.setError("您输入的密码不得小于6位", drawable);
                    ifboo[1] = false;
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mEtConfirmPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String pwd = mEtPassword.getText().toString().trim();
                String newPwd = mEtConfirmPassword.getText().toString().trim();
                if (newPwd.length() >= 6) {
                    if (pwd.equals(newPwd)) {
                        Drawable drawable = getResources().getDrawable(R.drawable.offline_notebook_synced);
                        drawable.setBounds(0, 0, 60, 60);
//                        if(ifboo[2]){
//                            edNewPass.setCompoundDrawables(null, null, drawable, null);
//                            return;
//                        }
                        mEtConfirmPassword.setError("正确", drawable);
                        ifboo[2] = true;
                        mBtRegister.setEnabled(true);
                    } else {
                        Drawable drawable = getResources().getDrawable(R.drawable.offline_notebook_not_synced);
                        drawable.setBounds(0, 0, 60, 60);
                        mEtConfirmPassword.setError("您两次输入的密码不相同", drawable);
                        ifboo[2] = false;
                        mBtRegister.setEnabled(false);
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mEtVercode.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String strCode = mEtVercode.getText().toString().trim();
                if (strCode.length() == 6) {
                    if (strCode.equals(codeKey)) {
                        Drawable drawable = getResources().getDrawable(R.drawable.offline_notebook_synced);
                        drawable.setBounds(0, 0, 60, 60);
//                        if (ifboo[3]) {
//                            edCode.setCompoundDrawables(null, null, drawable, null);
//                            return;
//                        }
                        mEtVercode.setError("正确", drawable);
                        ifboo[3] = true;
                    } else {
                        Drawable drawable = getResources().getDrawable(R.drawable.offline_notebook_not_synced);
                        drawable.setBounds(0, 0, 60, 60);
                        mEtVercode.setError("您输入的验证码不正确", drawable);
                        ifboo[3] = false;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }

    /**
     * 验证手机号是否注册
     *
     * @param phone
     */
    private void checkPhoneState(final String phone) {
        Observable.create(new Observable.OnSubscribe<BaseReturnBean>() {
            @Override
            public void call(Subscriber<? super BaseReturnBean> subscriber) {
                HashMap<String, Object> sendMap = new HashMap<>();
                sendMap.put("user_mobile", phone);
                BaseReturnBean bean = OkHttpUtils.initHttp(Constants.isRegPhone, sendMap);
                if (bean != null) {
                    subscriber.onNext(bean);
                } else {
                    subscriber.onError(new HttpException());
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<BaseReturnBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable throwable) {
                hideWaitDialog();
                throwable.printStackTrace();
            }

            @Override
            public void onNext(BaseReturnBean result) {
                hideWaitDialog();
                if (result != null) {
//                    T.showSingleL(result.desc);
                    switch (result.code) {
                        case "010000": {
                            mLoadingIf.setVisibility(View.GONE);
                            Drawable drawable = getResources().getDrawable(R.drawable.offline_notebook_synced);
                            drawable.setBounds(0, 0, 60, 60);
                            mEtInputMobile.setError("可以注册", drawable);
                            getVerCode(phone);
                            ifboo[0] = true;
                        }
                        break;
                        case "010102": {
                            mLoadingIf.setVisibility(View.GONE);
                            Drawable drawable = getResources().getDrawable(R.drawable.offline_notebook_not_synced);
                            drawable.setBounds(0, 0, 60, 60);
                            mEtInputMobile.setError("您的手机号已经被注册了", drawable);
                            ifboo[0] = false;
                        }
                        break;
                        case "010104": {
                            mLoadingIf.setVisibility(View.GONE);
                            Drawable drawable = getResources().getDrawable(R.drawable.offline_notebook_not_synced);
                            drawable.setBounds(0, 0, 60, 60);
                            mEtInputMobile.setError("您的手机号有误请检查", drawable);
                            ifboo[0] = false;
                        }
                        break;
                        case "010203": {
                            mLoadingIf.setVisibility(View.GONE);
                            Drawable drawable = getResources().getDrawable(R.drawable.offline_notebook_not_synced);
                            drawable.setBounds(0, 0, 60, 60);
                            mEtInputMobile.setError("验证发现系统级错误，请稍后再试！", drawable);
                            ifboo[0] = false;
                        }
                        break;

                    }
                } else {
                    T.showSingleL("请求失败");
                }
            }
        });
    }

    /**
     * 获取验证码
     *
     * @param phone
     */
    private void getVerCode(final String phone) {
        Observable.create(new Observable.OnSubscribe<BaseReturnBean>() {
            @Override
            public void call(Subscriber<? super BaseReturnBean> subscriber) {
                HashMap<String, Object> sendMap = new HashMap<>();
                sendMap.put("user_mobile", phone);
                BaseReturnBean bean = OkHttpUtils.initHttp(Constants.simulationVerifyCode, sendMap);
                if (bean != null) {
                    subscriber.onNext(bean);
                } else {
                    subscriber.onError(new HttpException());
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<BaseReturnBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable throwable) {
                hideWaitDialog();
                throwable.printStackTrace();
            }

            @Override
            public void onNext(BaseReturnBean result) {
                hideWaitDialog();
                if (result != null) {
                    codeKey = JSONUtil.getString(result.data, "verify_code", "");
                    mTvVercodeImg.setText(codeKey);
                } else {
                    T.showSingleL("请求失败");
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_vercode_img) {
            String phone = mEtInputMobile.getText().toString().trim();
            getVerCode(phone);
        } else if (v.getId() == R.id.bt_register) {
            requestRegister();
        }
    }

    private void requestRegister() {
        final HashMap<String, Object> sendMap = new HashMap<>();
        String phone = mEtInputMobile.getText().toString().trim();
        String pwd = mEtPassword.getText().toString().trim();
        String strCode = mEtVercode.getText().toString().trim();
        sendMap.put("user_mobile", phone);
        sendMap.put("user_newpwd", pwd);
        sendMap.put("verify_code", strCode);
        Observable.create(new Observable.OnSubscribe<BaseReturnBean>() {
            @Override
            public void call(Subscriber<? super BaseReturnBean> subscriber) {
                BaseReturnBean bean = OkHttpUtils.initHttp(Constants.findPwd, sendMap);
                if (bean != null) {
                    subscriber.onNext(bean);
                } else {
                    subscriber.onError(new HttpException());
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<BaseReturnBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable throwable) {
                hideWaitDialog();
                throwable.printStackTrace();
            }

            @Override
            public void onNext(BaseReturnBean result) {
                hideWaitDialog();
                if (result != null) {
                    Tools.cleanUserInfo(mContext);
                    String user_mobile = JSONUtil.getString(result.data, "user_mobile", "");
                    PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_MOBILE, user_mobile);
                    finish();
                } else {
                    T.showSingleL("请求失败");
                }
            }
        });
    }
}
